import $http from '@/common/http.js'
import $store from '@/store/index.js'
import {
  queryMembers
} from '@/common/api/member.js'
export const getOrderDetail = async (orderNo) => {
  const service = `srvretail_store_order_select`
  const url = `/retail/select/${service}`
  const req = {
    "serviceName": "srvretail_store_order_select",
    "colNames": ["*"],
    "condition": [{
      colName: 'order_no',
      ruleType: 'eq',
      value: orderNo
    }],
    "page": {
      "pageNo": 1,
      "rownumber": 1
    }
  }
  if (orderNo) {
    let res = await $http.post(url, req)
    if (Array.isArray(res.data.data) && res.data.data.length > 0) {
      let orderInfo = res.data.data[0]
      const req2 = {
        "serviceName": "srvretail_order_detail_select",
        "colNames": ["*"],
        "condition": [{
          "colName": "order_no",
          "ruleType": "eq",
          "value": orderNo
        }],
        "page": {
          "pageNo": 1,
          "rownumber": 200
        }
      }
      const res2 = await $http.post(`/retail/select/srvretail_order_detail_select`, req2)
      if (res2?.data?.state === "SUCCESS") {
        orderInfo.cartData = res2.data.data.map(item => {
          if (item.goods_num) {
            item.amount = item.goods_num
          }
          return item
        })
      }
      if (orderInfo?.member_no && $store?.state?.$memberList) {
        const curMemberInfo = $store?.state?.$memberList.find(item => item.menber_no == orderInfo?.member_no)
        if (curMemberInfo) {
          $store.commit('SET_STATE', {
            key: '$curMember',
            value: curMemberInfo
          })
        }
      }
      return orderInfo
    }
  }
}

export const createOrder = async (e) => {
  // const {
  //   order_total_amount,
  //   order_amount,
  //   member_no,
  //   remark,
  //   sales_clerk,
  //   order_detail,
  //   order_pay,
  //   discount_type,
  //   discount_mode,
  //   discount_reduction_amount,
  //   discount_reason,
  //   free_discount_amount,
  //   member_discount,
  //   cash_reduction_amount
  // } = e

  const url = `/retail/operate/srvretail_order_add_payment`
  const req = [{
    "serviceName": "srvretail_order_add_payment",
    "data": [{
      ...e,
      // order_total_amount,
      // order_amount,
      // member_no,
      // remark,
      // sales_clerk,
      // order_detail,
      // order_pay,
      // discount_type,
      // discount_mode,
      // discount_reduction_amount,
      // discount_reason,
      // free_discount_amount,
      // member_discount,
      // cash_reduction_amount,
    }]
  }]
  const res = await $http.post(url, req)
  queryMembers()
  if (res?.data?.state === 'SUCCESS') {
    return res?.data?.response[0]?.response?.effect_data[0]
  } else {
    if (res?.data?.resultMessage) {
      uni.showModal({
        title: '提示',
        content: res?.data?.resultMessage,
        showCancel: false
      })
    }
    return false
  }
}

export const payOrder = async (e) => {
  const {
    store_no,
    order_no,
    pay_type,
    member_no,
    amount,
    remark
  } = e
  const url = `/retail/operate/srvretail_order_payment`
  const req = [{
    "serviceName": "srvretail_order_payment",
    "data": [{
      store_no,
      order_no,
      pay_type,
      member_no,
      amount,
      remark
    }]
  }]
  let res = ''
  try {
    res = await $http.post(url, req)
    queryMembers()
    if (res?.data?.state === 'SUCCESS') {
      return res?.data?.response[0]?.response?.effect_data[0]
    } else {
      if (res?.data?.resultMessage) {
        uni.showModal({
          title: '提示',
          content: res?.data?.resultMessage,
          showCancel: false
        })
      }
    }
  } catch (e) {
    //TODO handle the exception
    console.log(e);
    return e
  }
}

/**
 * 扫码支付
 */
export const mobilePay = async (e, orderAmount) => {
  let {
    order_no,
    pay_way,
    authCode,
    member_no,
    amount,
    remark
  } = e
  if (orderAmount && !isNaN(Number(orderAmount)) && orderAmount > 0) {
    amount = orderAmount
  }
  const url = `/retail/operate/srvls_b_scan_c_pay`
  const req = [{
    "serviceName": "srvls_b_scan_c_pay",
    "data": [{
      order_no,
      pay_way,
      authCode,
      member_no,
      amount,
      remark,
      "channel_source": "台式消费机", //订单来源
    }]
  }]
  let res = ''
  try {
    res = await $http.post(url, req)
    queryMembers()
    if (res?.data?.resultCode === 'USERPAYING') {
      return 'USERPAYING'
    } else if (res?.data?.resultCode === 'SUCCESS') {
      return true
    } else {
      if (res?.data?.resultMessage) {
        uni.showModal({
          title: '提示',
          content: res?.data?.resultMessage,
          showCancel: false
        })
      }
      return false
    }
  } catch (e) {
    //TODO handle the exception
    console.log(e);
    return e
  }
}
/**
 * 刷新订单支付状态
 */
export const refreshOrderState = (orderNo) => {
  return new Promise(resolve => {
    let timer = null;
    const interval = setInterval(() => {
      queryOrderInfo(orderNo).then((state) => {
        if (state === true) {
          clearTimeout(timer)
          clearInterval(interval)
          resolve({
            state: true,
            message: '支付成功'
          })
        }
      })
    }, 1000)
    timer = setTimeout(() => {
      resolve({
        message: '支付超时'
      })
      clearInterval(interval)
    }, 20 * 1000)
  })
}

const queryOrderInfo = async (orderNo) => {
  const service = `srvretail_store_order_select`
  const url = `/retail/select/${service}`
  const req = {
    "serviceName": "srvretail_store_order_select",
    "colNames": ["*"],
    "condition": [{
      colName: 'order_no',
      ruleType: 'eq',
      value: orderNo
    }],
    "page": {
      "pageNo": 1,
      "rownumber": 1
    }
  }
  const res = await $http.post(url, req)
  let data = null
  if (res?.data?.state === 'SUCCESS' && Array.isArray(res.data.data) && res.data.data.length > 0) {
    data = res.data.data[0]
  }
  return data?.order_state === '已结账'
}
